package com.wei.service_vod.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.wei.service_base.exception.XueYuanException;
import com.wei.service_vod.service.VodService;
import com.wei.service_vod.util.ConstantPropertiesUtil;
import com.wei.service_vod.util.InitObject;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;


/**
 * @author wjx
 * @ClassName VodServiceImpl
 * @description: TODO
 * @date 2022-11-30 22:47
 * @version: 1.0
 */
@Service
public class VodServiceImpl implements VodService {
    /**
     * 文件流上传接口
     *
     * @param file
     * @return
     */
    @Override
    public String uploadToAliyun(MultipartFile file) {

        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String fileName = file.getOriginalFilename();
        String title = UUID.randomUUID().toString(true);
        InputStream is = null;

        try {
            is = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //new UploadStreamRequest(key,secret,阿里云存储的视频名称,上传的视频名称,文件流);
        UploadStreamRequest request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, fileName, is);

        UploadVideoImpl uploadVideo = new UploadVideoImpl();
        UploadStreamResponse response = uploadVideo.uploadStream(request);

        String videoId = response.getVideoId();

        return videoId;
    }

    @Override
    public void removeBatch(List<String> vidList) {
        DefaultAcsClient client = null;
        try {
            client = InitObject.initVodClient(ConstantPropertiesUtil.KEY_ID, ConstantPropertiesUtil.KEY_SECRET);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new XueYuanException(20001, e.getMessage());
        }

        DeleteVideoRequest request = new DeleteVideoRequest();
        request.setVideoIds(String.join(",", vidList));

        try {
            DeleteVideoResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
    }
}
